package video.background.Filter;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.interfaces.Claim;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import video.background.Dao.UserDao;
import video.background.Utils.JwtUtils;
import video.background.Utils.Result;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * @program: video-backgroud
 * @description:
 * @author: hlt
 * @create: 2023-08-17 11:31
 **/
@Slf4j
@WebFilter(filterName = "userFilter", urlPatterns = "/users/*")
@CrossOrigin(origins = "*", maxAge = 3600)
public class UserFilter implements Filter{
    @Autowired
    private UserDao userDao;

    private static final String SECRET_KEY = "super_Audio_Recognize_By_QMX";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        final HttpServletRequest request = (HttpServletRequest) req;
        final HttpServletResponse response = (HttpServletResponse) res;

        response.setCharacterEncoding("UTF-8");
        //获取header里的token
        final String token = request.getHeader("Authorization");

        // 设置过滤器里的例外
        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            chain.doFilter(request, response);
        }
        else {
            //验证token
            Map<String, Claim> stringClaimMap = JwtUtils.verifyToken(token);
            if (stringClaimMap != null) {
                // 验证通过则继续处理请求
                chain.doFilter(request, response);
            }else{
//                sendError(response, 40027, "Token已过期或无效");
                System.out.println("向前端发送错误信息！");
                returnJson(response,Result.Error("Token已过期或无效",null));
                return;
            }
        }
    }

    @Override
    public void destroy() {
    }

    private void sendError(HttpServletResponse response, int status, String message) throws IOException {
        PrintWriter writer = null;
        try {
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(status);
            writer = response.getWriter();
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            writer.close();
        }
    }

    private void returnJson(ServletResponse response, Result result) {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(result);
            System.out.println("错误信息发送成功！");
        } catch (IOException e) {
            log.error("response error", e);
        } finally {
            if (writer != null)
                writer.close();
        }
    }
}
